# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

import logging

from odoo import api, fields, models, _
from odoo.exceptions import AccessDenied, UserError

_logger = logging.getLogger(__name__)


class CrSafetyGroup(models.Model):
    _name = "cr.safety.hr.group"
    _description = "cr.safety.hr.group"

    code = fields.Char()
    name = fields.Char()


class CrSafetyDeptGroup(models.Model):
    _name = "cr.safety.hr.dept.group"
    _description = "cr.safety.hr.dept.group"

    code = fields.Char()
    name = fields.Char()


class CrSafetyDeptGroup2(models.Model):
    _name = "cr.safety.hr.dept.group2"
    _description = "cr.safety.hr.dept.group2"

    code = fields.Char()
    name = fields.Char()


class Department(models.Model):
    _inherit = ['hr.department']

    code = fields.Char()

    # 部门分组, 考核时按照分组,进行组内排序
    group_id = fields.Many2one('cr.safety.hr.dept.group', 'group_id')

    # 部门分组, 计算三率排名时 按照这个分组
    group2_id = fields.Many2one('cr.safety.hr.dept.group2', 'group2_id')

    # 科室/车间/中间站/班组 都是部门, 车间下设班组
    # 专业干部的 专业也是 部门
    type = fields.Selection([
        ('dept', '部门'),
        ('major', '专业'),
        ('workshop', '车间'),
        ('station', '中间站'),
        ('team', '班组')], default='dept')


class Job(models.Model):
    _inherit = ['hr.job']

    # 职工端和干部端, 按照职位分开
    type = fields.Selection([
        ('staff', '职工'),
        ('manager', '干部')], default='manager')


class HrEmployee(models.Model):
    """
    """
    _inherit = 'hr.employee'

    image_signature = fields.Image()

    job_type = fields.Selection([
        ('staff', '职工'),
        ('manager', '干部')], related='job_id.type')

    user_login = fields.Char(related='user_id.login')

    # 干部端 权限组
    group_id = fields.Many2one('cr.safety.hr.group', 'group_id')
    group_code = fields.Char(related='group_id.code')
    confirm_user = fields.Many2one('hr.employee', 'id',)
    confirm_user_name = fields.Char(related="confirm_user.name")
    confirm_user_id = fields.Integer(related="confirm_user.id")

    default_confirm_user = fields.Many2one('hr.employee', 'id')

    # 员工端 班组
    team_id = fields.Many2one('hr.department', 'team_id', )

    # 部门的分组, 考核时干部进行组内排序
    department_group_id = fields.Many2one(
        'cr.safety.hr.dept.group', 'department_group_id',
        related='department_id.group_id')

    # 干部的专业
    major_id = fields.Many2one('hr.department', 'major_id', )

    password2 = fields.Char()

    def name_get(self):
        result = []
        for rec in self:
            name = "[%s]%s" % (rec.barcode, rec.name)
            result.append((rec.id, name))
        return result

    @api.model
    def create(self, values):
        login = values.get('user_login')
        password = values.get('user_password')

        name = values.get('name') or login
        # email = values.get('user_email') or login

        user = None

        if login and password:
            user = self.env['res.users'].search([('login', '=', login)])
            if not user:
                user = self.env['res.users'].create({
                    'employee_flag': 1,
                    'login': login,
                    'password': password,
                    'name': name,
                    'email': login
                })

            group_id = self.env['ir.model.data'].xmlid_to_res_id('base.group_system', True)
            user.groups_id += self.env['res.groups'].browse(group_id)

        if login:
            del values['user_login']

        if password:
            del values['user_password']

        if user:
            values['user_id'] = user.id

        return super(HrEmployee, self).create(values)

    def write(self, values):
        login = values.get('user_login')
        # email = values.get('user_email') or login
        name = values.get('name')
        if 'user_password_default' in values.keys():
            password = values.get('user_password_default')
            del values['user_password_default']

        user_vals = {}

        if login:
            user_vals['login'] = login
            del values['user_login']

        if name:
            user_vals['name'] = name

        ret = super(HrEmployee, self).write(values)

        if user_vals:
            if self.user_id:
                if name and name != self.user_id.name:
                    self.user_id.write(user_vals)
                elif login and login != self.user_id.login:
                    self.user_id.write(user_vals)

            else:
                user_vals['name'] = self.name
                user_vals['email'] = login
                user_vals['password'] = password
                user = self.user_id.create(user_vals)
                group_id = self.env['ir.model.data'].xmlid_to_res_id('base.group_system', True)
                user.groups_id += self.env['res.groups'].browse(group_id)
                self.user_id = user

        return ret

    def unlink(self):
        user = self.user_id
        partner = self.user_partner_id

        ret = super(HrEmployee, self).unlink()

        if user:
            user.unlink()
        if partner:
            partner.unlink()

        return ret

    # def _compute_default_confirm_user(self):
    #     if self.group_code == '1st':
    #         self.default_confirm_user = self.search([('department_id','=',self.department_id),('group_code','=','2nd')])
    #     else:
    #         self.default_confirm_user = None

class ResUsers(models.Model):
    """
    """
    _inherit = 'res.users'

    image_signature = fields.Image(related='employee_id.image_signature')

    @api.model
    def change_password2(self, old_passwd, new_passwd):
        """Change current user password2. Old password2 must be provided explicitly
        to prevent hijacking an existing user session, or for cases where the cleartext
        password is not used to authenticate requests.

        :return: True
        :raise: odoo.exceptions.AccessDenied when old password2 is wrong
        :raise: odoo.exceptions.UserError when new password2 is not set or empty
        """

        password2 = self.env.user.employee_id.password2

        if not password2:
            password2 = '222222'

        if password2 != old_passwd:
            raise AccessDenied()

        if new_passwd:
            # use self.env.user here, because it has uid=SUPERUSER_ID
            return self.env.user.employee_id.write({'password2': new_passwd})

        raise UserError(_("Setting empty passwords is not allowed for security reasons!"))

    @api.model
    def create(self, values):
        _logger.info(str(values))
        if "cr_emp_type" in values.keys() and "login" in values.keys() and values["cr_emp_type"] != 'none':
            user = self.search([('login', '=', values['login'])])
            if user:
                user.write({"cr_emp_type":values["cr_emp_type"],"card_id":values["login"],"cr_emp_ws_id":values['cr_emp_ws_id']})
                return user
        if 'employee_flag' in values.keys():
            del values['employee_flag']
            user_id = super(ResUsers, self).create(values)
        else:
            user_id = super(ResUsers, self).create(values)
            user_id.action_create_employee()
        return user_id
